package com.cloud.cloudBatis.session.impl;

import com.cloud.cloudBatis.config.Configuration;
import com.cloud.cloudBatis.config.MapperStatement;
import com.cloud.cloudBatis.mapper.UserMapper;
import com.cloud.cloudBatis.session.Excutor;
import com.cloud.cloudBatis.session.SqlSession;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public class DefaultSqlSession implements SqlSession {
    private Excutor excutor;
    private Configuration configuration;
    public DefaultSqlSession(Excutor excutor, Configuration configuration) {
        this.excutor = excutor;
        this.configuration = configuration;
    }
    @Override
    public <T> T selectOne(String statement, Object parameter) {
        Map<String, MapperStatement> mapperMap = configuration.getMapperMap();
        MapperStatement mapperStatement = mapperMap.get(statement);
        List<T> list = null;
        try {
            list = (List<T>) excutor.query(mapperStatement, parameter);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        if (list != null && list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }

    @Override
    public <T> List<T> selectList(String statement, Object parameter) {
        Map<String, MapperStatement> mapperMap = configuration.getMapperMap();
        MapperStatement mapperStatement = mapperMap.get(statement);
        List<T> list = null;
        try {
            list = (List<T>) excutor.query(mapperStatement, parameter);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return list;
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T> T getMapper(Class<T> clazz) {
        InvocationHandler invocationHandler = new MapperProxy(this);
        T instance = (T) Proxy.newProxyInstance(clazz.getClassLoader(),new Class[]{clazz}, invocationHandler);
        return instance;
    }
}
